package com.demo.juc.thread;

import java.util.concurrent.TimeUnit;

public class DeadlockDemo {

    public static void main(String[] args) {
        String lockA = "lockA";
        String lockB = "lockB";
        new Thread(new MyThread3(lockA,lockB),"T1").start();
        new Thread(new MyThread3(lockB,lockA),"T2").start();
    }
}


class MyThread3 implements Runnable{
    private String lockA;
    private String lockB;

    public MyThread3(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA){
            //lockA想拿B
            System.out.println(Thread.currentThread().getName() + "lock"+ lockA + "=> get" + lockB);
            try {
                TimeUnit.SECONDS.sleep(3);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lockB){
                //B想拿A
                System.out.println(Thread.currentThread().getName() + "lock" + lockB + "=> get" + lockA);
            }
        }
    }
}
